package com.truckdispatching.database;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import com.truckdispatching.entity.Notification;

public class NotificationSql {

	public static final String TAG = NotificationSql.class.getSimpleName();

	private static NotificationSql instance = null;
	private final String TABLE_NAME = "Notification";

	private final String KEY_ID = "id";
	private final String KEY_TIME = "time";
	private final String KEY_CONTENT = "content";

	public static synchronized NotificationSql getInstance() {
		if (null == instance) {
			instance = new NotificationSql();
		}
		return instance;
	}

	public void createTable(SQLiteDatabase database) {
		if (database != null) {
			String sql = "create table if not exists " + TABLE_NAME
					+ "( "
					+ KEY_ID + " INTEGER PRIMARY KEY,"
					+ KEY_TIME + " INTEGER,"
					+ KEY_CONTENT + " VARCHAR(20)"
					+ " )";
			database.execSQL(sql);
		}
	}

	public void dropTable() {
		if (DataBaseOpenHelper.mDataBase != null) {
			String sql = "drop table if exists " + TABLE_NAME;
			DataBaseOpenHelper.mDataBase.execSQL(sql);
		}
	}

	public long insert(Notification notification) {
		// 插入数据库
		if (DataBaseOpenHelper.mDataBase != null) {
			ContentValues values = new ContentValues();
			values.put(KEY_TIME, notification.time);
			values.put(KEY_CONTENT, notification.content);
			return DataBaseOpenHelper.mDataBase.insert(TABLE_NAME, null, values);
		}
		return 0;
	}

	public long update(Notification notification) {
		if (DataBaseOpenHelper.mDataBase != null) {
			ContentValues values = new ContentValues();
			values.put(KEY_ID, notification.id);
			values.put(KEY_TIME, notification.time);
			values.put(KEY_CONTENT, notification.content);
			return DataBaseOpenHelper.mDataBase.update(TABLE_NAME, values,
					KEY_ID + " = ?", new String[] { String.valueOf(notification.id)
				});
		}
		return 0;
	}

	public void deleteById(int id) {
		// 删除数据库
		if (DataBaseOpenHelper.mDataBase != null) {
			DataBaseOpenHelper.mDataBase.delete(TABLE_NAME, KEY_ID + " = ?", new String[] { String.valueOf(id) });
		}
	}

	public void deleteAll() {
		if (DataBaseOpenHelper.mDataBase != null) {
			DataBaseOpenHelper.mDataBase.delete(TABLE_NAME, null, null);
		}
	}

	public ArrayList<Notification> findAll() {
		try {
			if (DataBaseOpenHelper.mDataBase != null) {
				ArrayList<Notification> ns = (ArrayList<Notification>) DataBaseOpenHelper.mDataBase.query(TABLE_NAME,
						null,
						null, null, null, null, null);
				return ns;
			}
		} catch (Exception e) {
		}
		return null;
	}

}
